<template>
  <view class="charging-rule-wait-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="月卡（有效）" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 停车场搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.parkingLot" :clearabled="true" :showAction="true" 
                placeholder="请输入停车场" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
          <up-tabs :list="statusList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="charging-rule-wait-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              月卡名称：<text class="number">{{ item.cardName }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">售卖日期：</text>
                <text class="value">{{ item.saleDate }}</text>
              </view>
              <view class="item">
                <text class="label">生效日期：</text>
                <text class="value">{{ item.effectiveDate }}</text>
              </view>
              <view class="item">
                <text class="label">售卖价格：</text>
                <text class="value amount">¥{{ item.price }}</text>
              </view>
              <view class="item">
                <text class="label">月卡可用时长：</text>
                <text class="value">{{ item.validPeriod }}</text>
              </view>
              <view class="item">
                <text class="label">发布数量：</text>
                <text class="value">{{ item.totalQuantity }}</text>
              </view>
              <view class="item">
                <text class="label">单车牌限购：</text>
                <text class="value">{{ item.purchaseLimit }}张</text>
              </view>
              <view class="item">
                <text class="label">已售卖数量：</text>
                <text class="value">{{ item.soldQuantity }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="checkbox-box">
              </view>
              <view class="operate">
                <up-button type="primary" text="生效场地" class="custom-style" @click.stop="viewVenues(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 状态列表
const statusList = [
  { name: '全部' },
  { name: '在售' },
  { name: '已售完' },
];
const currentStatus = ref(0);

// 搜索表单
const searchForm = reactive({
  dateRange: [], // 日期范围
  parkingLot: '',
  status: 0, // 0: 全部, 1: 在售, 2: 已售完
});

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  searchForm.dateRange = e;
  paging.value?.reload();
};

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 汇总数据
const summaryData = ref({
  totalCount: 0,
  avgParkingHours: '0',
  totalAmount: '0.00'
});

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentStatus.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentStatus.value = newIndex;
  searchForm.status = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理搜索
const handleSearch = () => {
  paging.value?.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.parkingLot = '';
  searchForm.dateRange = [];
  paging.value?.reload();
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理日期范围参数
    const params = {
      pageNo,
      pageSize,
      parkingLot: searchForm.parkingLot,
      status: searchForm.status
    };
    
    // 如果有日期范围，添加到参数中
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getMonthlyCardList(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: Array.from({ length: 10 }, (_, i) => ({
        id: `${pageNo}-${i}`,
        cardName: `${['标准', '优惠', '特惠', 'VIP'][Math.floor(Math.random() * 4)]}月卡${i + 1}`,
        saleDate: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
        effectiveDate: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
        price: (Math.random() * 500 + 100).toFixed(2),
        validPeriod: `${Math.floor(Math.random() * 6) + 1}个月`,
        totalQuantity: Math.floor(Math.random() * 1000) + 100,
        purchaseLimit: Math.floor(Math.random() * 5) + 1,
        soldQuantity: Math.floor(Math.random() * 100),
        venues: Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, j) => (
          `${['首都机场', '北京南站', '西单商场', '王府井', '三里屯', '国贸', '望京'][Math.floor(Math.random() * 7)]}停车场${j + 1}`
        ))
      }))
    };
    
    // 更新汇总数据
    updateSummaryData(mockData.list);
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取月卡列表数据失败:', error);
    paging.value.complete(false);
  }
};

// 更新汇总数据
const updateSummaryData = (list) => {
  if (!list || list.length === 0) return;
  
  // 计算总售卖金额
  const totalAmount = list.reduce((sum, item) => sum + parseFloat(item.price), 0).toFixed(2);
  
  // 计算总售卖数量
  const totalSold = list.reduce((sum, item) => sum + item.soldQuantity, 0);
  
  summaryData.value = {
    totalCount: list.length,
    totalSold: totalSold,
    totalAmount: totalAmount
  };
};

// 查看详情
const viewDetail = (item) => {
  uni.navigateTo({
    url: `/pages/monthly-card/detail?id=${item.id}`
  });
};

// 查看生效场地
const viewVenues = (item) => {
  uni.showModal({
    title: '生效场地列表',
    content: item.venues.join('\n'),
    showCancel: false,
    confirmText: '确定'
  });
};

// 返回按钮处理
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

onMounted(() => {
  // 初始化加载数据
  paging.value?.reload();
});
</script>

<style lang="scss" scoped>
.charging-rule-wait-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    margin-bottom: 10px;
    
    .filter-item {
      margin-bottom: 10px;
      
      .filter-label {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
        display: block;
      }
      
      .time-range {
        display: flex;
        align-items: center;
        
        .range-separator {
          margin: 0 10px;
        }
      }
      
      .time-picker {
        background-color: #fff;
        border-radius: 4px;
        padding: 8px 12px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        width: 100%;
      }
    }
  }
  
  .summary-section {
    display: flex;
    justify-content: space-between;
    padding: 15px;
    background-color: #fff;
    border-radius: 8px;
    margin: 0 15px 15px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    
    .summary-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .summary-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 5px;
      }
      
      .summary-value {
        font-size: 16px;
        color: #333;
        font-weight: bold;
        
        &.amount {
          color: #f56c6c;
        }
        
        &.count {
          color: #409eff;
        }
      }
    }
  }
}

.charging-rule-wait-list {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>